package com.encryptdemo.encrypt.aop;


import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import com.encryptdemo.encrypt.annotation.EncryptDecrypt;
import com.encryptdemo.encrypt.util.AESUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;

@Component
public class EncryptDecryptInterceptor implements HandlerInterceptor {

    private final String key = "1234567890123456";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method.getMethod().isAnnotationPresent(EncryptDecrypt.class)) {
                String encryptedBody = extractFirstFieldValue(request);
//                String encryptedBody = getBody(request);

                String decryptedBody = AESUtil.decryptByAes(encryptedBody, key);
                request.setAttribute("decryptedData", decryptedBody);
            }
        }
        return true;
    }

    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }
    private String extractFirstFieldValue(HttpServletRequest request) throws IOException {
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 解析请求体为 JsonNode
        JsonNode jsonNode = objectMapper.readTree(request.getReader());

        // 获取第一个字段的值
        Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
        if (fields.hasNext()) {
            Map.Entry<String, JsonNode> firstField = fields.next();
            return firstField.getValue().asText(); // 返回第一个字段的值
        }

        throw new IllegalArgumentException("Request body is empty or invalid JSON");
    }


    private String getBody(HttpServletRequest request) throws IOException {
        byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
        return new String(readBytes, StandardCharsets.UTF_8);
    }
}
